<template>
  <div class="login-container">
    <div class="login-card">
      <h2 class="login-title">用户登录</h2>
      
      <form @submit.prevent="handleLogin" class="login-form">
        <!-- 用户名输入 -->
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            type="text"
            id="username"
            v-model="formData.username"
            required
            placeholder="请输入用户名"
            class="form-input"
          >
        </div>
        
        <!-- 密码输入 -->
        <div class="form-group">
          <label for="password">密码</label>
          <div class="password-input">
            <input
              :type="showPassword ? 'text' : 'password'"
              id="password"
              v-model="formData.password"
              required
              placeholder="请输入密码"
              class="form-input"
            >
            <button
              type="button"
              @click="showPassword = !showPassword"
              class="toggle-password"
              aria-label="切换密码可见性"
            >
              <i class="fa" :class="showPassword ? 'fa-eye-slash' : 'fa-eye'"></i>
            </button>
          </div>
        </div>
        
        <!-- 确认密码输入 -->
        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <div class="password-input">
            <input
              :type="showConfirmPassword ? 'text' : 'password'"
              id="confirmPassword"
              v-model="formData.confirmPassword"
              required
              placeholder="请再次输入密码"
              class="form-input"
            >
            <button
              type="button"
              @click="showConfirmPassword = !showConfirmPassword"
              class="toggle-password"
              aria-label="切换密码可见性"
            >
              <i class="fa" :class="showConfirmPassword ? 'fa-eye-slash' : 'fa-eye'"></i>
            </button>
          </div>
          <div v-if="formData.password !== formData.confirmPassword && formData.confirmPassword" class="error-message">
            两次输入的密码不一致
          </div>
        </div>
        
        <!-- 验证码 -->
        <div class="form-group">
          <label for="captcha">验证码</label>
          <div class="captcha-container">
            <input
              type="text"
              id="captcha"
              v-model="formData.captcha"
              required
              placeholder="请输入验证码"
              class="form-input captcha-input"
            >
            <div class="captcha-image-container">
              <img 
                :src="captchaUrl" 
                alt="验证码图片" 
                class="captcha-image"
                @click="refreshCaptcha"
              >
              <button 
                type="button" 
                @click="refreshCaptcha"
                class="refresh-captcha"
                aria-label="刷新验证码"
              >
                <i class="fa fa-refresh"></i>
              </button>
            </div>
          </div>
        </div>
        
        <!-- 登录按钮 -->
        <button 
          type="submit" 
          class="login-button"
          :disabled="isLoading"
        >
          <span v-if="!isLoading">登录</span>
          <span v-if="isLoading">登录中...</span>
        </button>
        <!-- 前往注册按钮 -->
        <button 
          type="button" 
          class="register-btn"
          @click="$router.push('/register')"
        >
          还没有账号？去注册
        </button>
      </form>

      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-alert">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';

// 表单数据
const formData = ref({
  username: '',
  password: '',
  confirmPassword: '',
  captcha: ''
});

// 状态管理
const showPassword = ref(false);
const showConfirmPassword = ref(false);
const captchaUuid = ref('');
const captchaUrl = ref('');
const isLoading = ref(false);
const errorMessage = ref('');

// 路由
const router = useRouter();

// 生成UUID并获取验证码
const generateCaptcha = () => {
  captchaUuid.value = uuidv4();
  captchaUrl.value = `/api/user/verification/login/${captchaUuid.value}/`;
};


// const refreshVerification = () => {
//   verificationUuid.value = uuidv4();
//   verificationUrl.value = `/api/user/verification/register/${verificationUuid.value}/`;
// };

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha();
  formData.value.captcha = ''; // 清空输入的验证码
};

// 检查密码是否一致
const passwordsMatch = computed(() => {
  return formData.value.password === formData.value.confirmPassword;
});

// 处理登录
const handleLogin = async () => {
  // 简单验证
  if (!formData.value.username || !formData.value.password) {
    errorMessage.value = '用户名和密码不能为空';
    return;
  }
  
  if (!passwordsMatch.value) {
    errorMessage.value = '两次输入的密码不一致';
    return;
  }
  
  if (!formData.value.captcha) {
    errorMessage.value = '请输入验证码';
    return;
  }
  
  try {
    isLoading.value = true;
    errorMessage.value = '';
    
    // 发送登录请求
    const response = await axios.post('/user/login/', {
      username: formData.value.username,
      password: formData.value.password,
      verify: formData.value.captcha,
      uuid: captchaUuid.value
    });
    
    // 存储token
    if (response.data.token) {
      localStorage.setItem('token', response.data.token);
      // 登录成功，跳转到首页
      router.push('/home');
    }
  } catch (err) {
    console.error('登录失败:', err);
    errorMessage.value = err.response?.data?.message || '登录失败，请检查用户名、密码或验证码';
    // 登录失败时刷新验证码
    refreshCaptcha();
  } finally {
    isLoading.value = false;
  }
};

// 页面加载时生成验证码
onMounted(() => {
  generateCaptcha();
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 20px;
  background: linear-gradient(135deg, #fff 0%, #fff5f5 100%);
}

.login-card {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(255, 127, 80, 0.1);
}

.login-title {
  text-align: center;
  color: #ff6b6b;
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: 600;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #555;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ffd1dc;
  border-radius: 6px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.form-input:focus {
  outline: none;
  border-color: #ff6b6b;
  box-shadow: 0 0 0 3px rgba(255, 107, 107, 0.1);
}

.password-input {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #ff8fa3;
  cursor: pointer;
  font-size: 16px;
  padding: 5px;
}

.captcha-container {
  display: flex;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-image-container {
  position: relative;
  width: 140px;
  height: 40px;
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
  cursor: pointer;
  border: 1px solid #ffd1dc;
}

.refresh-captcha {
  position: absolute;
  right: 5px;
  top: 5px;
  background-color: rgba(255, 255, 255, 0.7);
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
  color: #ff6b6b;
}

.login-button {
  width: 100%;
  padding: 12px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.login-button:hover {
  background-color: #ff5252;
}

.login-button:disabled {
  background-color: #ffb7b2;
  cursor: not-allowed;
}

.error-message {
  color: #ff5252;
  font-size: 14px;
  margin-top: 5px;
}

.error-alert {
  margin-top: 15px;
  padding: 10px;
  background-color: #ffebee;
  color: #b71c1c;
  border-radius: 6px;
  text-align: center;
  font-size: 14px;
}

.register-btn {
  width: 100%;
  margin-top: 15px;
  padding: 12px;
  background-color: white; /* 白色注册按钮 */
  color: #dc3545; /* 红色文字 */
  border: 1px solid #dc3545;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.register-btn:hover {
  background-color: #f8d7da;
}
</style>
